package com.tb.ClassSchedule;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by guich on 2016/8/22.
 */
public class EditClassActivity extends AppCompatActivity implements View.OnClickListener {

    private Lesson lesson;
    public static EditClassActivity main;

    private TitleView title;

    public static Button   selectWeek;
    public static Button   selectSection;
    private       TextView tvClassName;
    private       TextView tvTeacherName;
    private       TextView tvAddress;

    private String className;
    private String teacherName;
    public static int startWeek;
    public static int endWeek;
    public static int weekday;
    public static int startSection;
    public static int endSection;
    private String address;
    private View delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_class);
        main = this;

        Bundle bundle = getIntent().getExtras();
        this.lesson = (Lesson) bundle.getSerializable("LessonInfo");

        initTitle();

        selectWeek = (Button) findViewById(R.id.select_week);
        selectWeek.setOnClickListener(this);
        selectSection = (Button) findViewById(R.id.select_section);
        selectSection.setOnClickListener(this);
        tvClassName = (TextView) findViewById(R.id.class_name);
        tvTeacherName = (TextView) findViewById(R.id.teacher_name);
        tvAddress = (TextView) findViewById(R.id.class_address);
        delete = findViewById(R.id.detail_delete);
        delete.setOnClickListener(this);

        initInfo();
    }

    private void initTitle(){
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("修改课程信息");
        setSupportActionBar(toolbar);
        //显示返回按钮
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            toolbar.setPadding(0,MainActivity.statusBarHeight,0,0);
        }
        toolbar.setBackgroundColor(MainActivity.sharedPreferences.getInt("color",MainActivity.DEFAULT_THEME));
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if(item.getItemId() == R.id.action_commit){
                    okAction();
                }
                return true;
            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            //处理返回按钮
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit,menu);
        return true;
    }

    private void initInfo(){
        tvClassName.setText(lesson.getName());
        tvTeacherName.setText(lesson.getTeacher());
        tvAddress.setText(lesson.getAddress());
        className = lesson.getName();
        teacherName = lesson.getTeacher();
        address = lesson.getAddress();

        String weekStr = "";
        if(lesson.getEndWeek() == lesson.getStartWeek()){
            weekStr = "第 " + lesson.getStartWeek() + " 周";
        }else{
            weekStr = "第 " + lesson.getStartWeek() + " 周 ~ 第 " + lesson.getEndWeek() + " 周";
        }
        selectWeek.setText(weekStr);
        weekday = lesson.getWeekday();
        startWeek = lesson.getStartWeek();
        endWeek = lesson.getEndWeek();

        String[] weekday = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        String sectionStr = "";
        if(lesson.getStartSection() == lesson.getEndSection()){
            sectionStr = weekday[lesson.getWeekday() - 1] + " : 第 " + lesson.getStartSection() + " 节";
        }else{
            sectionStr = weekday[lesson.getWeekday() - 1] + " : 第 " + lesson.getStartSection() + " 节 ~ 第 " + lesson.getEndSection() + " 节";
        }
        selectSection.setText(sectionStr);
        startSection = lesson.getStartSection();
        endSection = lesson.getEndSection();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.select_section:
                SectionSelector sectionSelector = new SectionSelector(this,lesson.getWeekday(),lesson.getStartSection(),lesson.getEndSection());
                sectionSelector.show();
                break;
            case R.id.select_week:
                WeekSelector weekSelector = new WeekSelector(this,lesson.getStartWeek(),lesson.getEndWeek());
                weekSelector.show();
                break;
            case R.id.title_ok_button:
                okAction();
                break;
            case R.id.detail_delete:
                deleteAction();
                break;
        }
    }

    private void okAction() {
        className = tvClassName.getText().toString();
        teacherName = tvTeacherName.getText().toString();
        address = tvAddress.getText().toString();

        if(className.equals("") ||
                selectSection.getText().equals("") ||
                selectWeek.getText().equals("")){
            Log.d("检测添加条件","不合法");
            AlertDialog.Builder builder = new AlertDialog.Builder(main);
            builder.setTitle("警告！");
            builder.setMessage("\n课程名称和上课时间都不给，臣妾做不到啊~");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            builder.show();

        }else {
            saveToDatabase();
            Log.d("修改成功",className + "\n"
                    + teacherName + "\n"
                    + address + "\n"
                    + startWeek + " ~ "+ endWeek + "\n"
                    + weekday + " : " + startSection + " ~ " + endSection + "\n"
            );
            Toast.makeText(main,"修改成功",Toast.LENGTH_SHORT).show();

            LessonViewActivity.main.initInfo(new Lesson(className,weekday,startSection,endSection,startWeek,endWeek,teacherName,address));
            MainActivity.main.draw();
            main.finish();
        }
    }

    private void deleteAction(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认提示");
        builder.setMessage("\n确认删除本课所有相关信息？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                LessonDatabaseHelper dbHelper = new LessonDatabaseHelper(MainActivity.main, "Lessons.db", null, 1);
                SQLiteDatabase       db       = dbHelper.getWritableDatabase();
                db.delete("Lesson","ClassName = ? and " +
                        "WeekDay = ? and " +
                        "StartSection = ? and " +
                        "EndSection = ? and " +
                        "StartWeek = ? and " +
                        "EndWeek = ? and " +
                        "TeacherName = ? and " +
                        "Address = ?",new String[]{
                        lesson.getName(),
                        "" + lesson.getWeekday(),
                        "" + lesson.getStartSection(),
                        "" + lesson.getEndSection(),
                        "" + lesson.getStartWeek(),
                        "" + lesson.getEndWeek(),
                        lesson.getTeacher(),
                        lesson.getAddress()});


                Toast.makeText(main,"删除成功！",Toast.LENGTH_SHORT).show();
                MainActivity.main.draw();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        builder.show();
    }




    private void saveToDatabase(){

        LessonDatabaseHelper dbHelper = new LessonDatabaseHelper(MainActivity.main, "Lessons.db", null, 1);
        SQLiteDatabase       db       = dbHelper.getWritableDatabase();

        ContentValues        values   = new ContentValues();
        values.put("ClassName", className);
        values.put("WeekDay", weekday);
        values.put("StartSection", startSection);
        values.put("EndSection", endSection);
        values.put("StartWeek", startWeek);
        values.put("EndWeek", endWeek);
        values.put("TeacherName", teacherName);
        values.put("Address", address);

        db.update("Lesson",values,"ClassName = ? and " +
                "WeekDay = ? and " +
                "StartSection = ? and " +
                "EndSection = ? and " +
                "StartWeek = ? and " +
                "EndWeek = ? and " +
                "TeacherName = ? and " +
                "Address = ?",new String[]{
                lesson.getName(),
                "" + lesson.getWeekday(),
                "" + lesson.getStartSection(),
                "" + lesson.getEndSection(),
                "" + lesson.getStartWeek(),
                "" + lesson.getEndWeek(),
                lesson.getTeacher(),
                lesson.getAddress()});
        values.clear();
    }



}
